package com.example.remotecontrol.data.repository

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.remotecontrol.data.model.Device
import com.example.remotecontrol.data.model.DeviceControlType
import com.example.remotecontrol.data.model.DeviceType
import com.example.remotecontrol.data.model.IrDeviceData
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

// 创建一个DataStore实例
private val Context.deviceDataStore by preferencesDataStore(name = "devices")

/**
 * 设备数据仓库
 * 负责管理设备数据的存储和检索
 */
@Singleton
class DeviceRepository @Inject constructor(
    @ApplicationContext private val context: Context
) {
    private val gson = Gson()
    private val deviceListKey = stringPreferencesKey("device_list")
    
    // 获取所有设备数据流
    val devices: Flow<List<Device>> = context.deviceDataStore.data
        .map { preferences ->
            val deviceJson = preferences[deviceListKey] ?: "[]"
            val type = object : TypeToken<List<Device>>() {}.type
            gson.fromJson(deviceJson, type) ?: emptyList()
        }
    
    // 获取收藏设备数据流
    val favoriteDevices: Flow<List<Device>> = devices
        .map { deviceList ->
            deviceList.filter { it.isFavorite }
        }
    
    // 获取按最后使用时间排序的设备数据流
    val recentDevices: Flow<List<Device>> = devices
        .map { deviceList ->
            deviceList.sortedByDescending { it.lastUsed }
        }

    // 获取按类型分组的设备数据流
    val devicesByType: Flow<Map<DeviceType, List<Device>>> = devices
        .map { deviceList ->
            deviceList.groupBy { it.type }
        }
    
    // 获取按房间分组的设备数据流
    val devicesByRoom: Flow<Map<String, List<Device>>> = devices
        .map { deviceList ->
            deviceList
                .filter { it.room.isNotBlank() }
                .groupBy { it.room }
        }
    
    /**
     * 添加或更新设备
     */
    suspend fun addOrUpdateDevice(device: Device) {
        context.deviceDataStore.edit { preferences ->
            val deviceJson = preferences[deviceListKey] ?: "[]"
            val type = object : TypeToken<MutableList<Device>>() {}.type
            val deviceList: MutableList<Device> = gson.fromJson(deviceJson, type) ?: mutableListOf()
            
            // 查找是否已存在此设备
            val existingIndex = deviceList.indexOfFirst { it.id == device.id }
            
            if (existingIndex >= 0) {
                // 更新现有设备
                deviceList[existingIndex] = device
            } else {
                // 添加新设备
                deviceList.add(device)
            }
            
            preferences[deviceListKey] = gson.toJson(deviceList)
        }
    }
    
    /**
     * 删除设备
     */
    suspend fun deleteDevice(deviceId: String) {
        context.deviceDataStore.edit { preferences ->
            val deviceJson = preferences[deviceListKey] ?: "[]"
            val type = object : TypeToken<MutableList<Device>>() {}.type
            val deviceList: MutableList<Device> = gson.fromJson(deviceJson, type) ?: mutableListOf()
            
            // 移除指定ID的设备
            deviceList.removeIf { it.id == deviceId }
            
            preferences[deviceListKey] = gson.toJson(deviceList)
        }
    }
    
    /**
     * 设置设备收藏状态
     */
    suspend fun setDeviceFavorite(deviceId: String, isFavorite: Boolean) {
        context.deviceDataStore.edit { preferences ->
            val deviceJson = preferences[deviceListKey] ?: "[]"
            val type = object : TypeToken<MutableList<Device>>() {}.type
            val deviceList: MutableList<Device> = gson.fromJson(deviceJson, type) ?: mutableListOf()
            
            // 查找并更新设备的收藏状态
            val deviceIndex = deviceList.indexOfFirst { it.id == deviceId }
            if (deviceIndex >= 0) {
                val device = deviceList[deviceIndex]
                deviceList[deviceIndex] = device.copy(isFavorite = isFavorite)
                preferences[deviceListKey] = gson.toJson(deviceList)
            }
        }
    }
    
    /**
     * 更新设备最后使用时间
     */
    suspend fun updateDeviceLastUsed(deviceId: String) {
        context.deviceDataStore.edit { preferences ->
            val deviceJson = preferences[deviceListKey] ?: "[]"
            val type = object : TypeToken<MutableList<Device>>() {}.type
            val deviceList: MutableList<Device> = gson.fromJson(deviceJson, type) ?: mutableListOf()
            
            // 查找并更新设备的最后使用时间
            val deviceIndex = deviceList.indexOfFirst { it.id == deviceId }
            if (deviceIndex >= 0) {
                val device = deviceList[deviceIndex]
                deviceList[deviceIndex] = device.copy(lastUsed = System.currentTimeMillis())
                preferences[deviceListKey] = gson.toJson(deviceList)
            }
        }
    }
    
    /**
     * 获取指定ID的设备
     */
    suspend fun getDeviceById(deviceId: String): Device? {
        val deviceJson = context.deviceDataStore.data.map { it[deviceListKey] ?: "[]" }.firstOrNull()
        val type = object : TypeToken<List<Device>>() {}.type
        val deviceList: List<Device> = gson.fromJson(deviceJson, type) ?: emptyList()
        
        return deviceList.find { it.id == deviceId }
    }
    
    /**
     * 创建默认示例设备数据（仅用于测试）
     */
    suspend fun createSampleDevices() {
        // 创建一些示例设备
        val sampleDevices = listOf(
            Device(
                name = "客厅电视",
                type = DeviceType.TV,
                brand = "三星",
                model = "UA55TU8800",
                room = "客厅",
                controlType = DeviceControlType.IR,
                irData = IrDeviceData(
                    addressCode = 0x0707,
                    commandMap = mapOf(
                        "POWER" to 0x02,
                        "VOLUME_UP" to 0x07,
                        "VOLUME_DOWN" to 0x0B
                    )
                ),
                isFavorite = true
            ),
            Device(
                name = "卧室空调",
                type = DeviceType.AC,
                brand = "格力",
                room = "卧室",
                controlType = DeviceControlType.IR,
                irData = IrDeviceData(
                    addressCode = 0x4040,
                    commandMap = mapOf(
                        "POWER" to 0x08,
                        "TEMP_UP" to 0x0C,
                        "TEMP_DOWN" to 0x0D
                    )
                )
            ),
            Device(
                name = "书房投影仪",
                type = DeviceType.PROJECTOR,
                brand = "明基",
                model = "W1110",
                room = "书房",
                controlType = DeviceControlType.IR,
                irData = IrDeviceData(
                    addressCode = 0x20DF,
                    commandMap = mapOf(
                        "POWER" to 0x10,
                        "SOURCE" to 0x12,
                        "MENU" to 0x43
                    )
                )
            )
        )
        
        // 保存示例设备数据
        context.deviceDataStore.edit { preferences ->
            preferences[deviceListKey] = gson.toJson(sampleDevices)
        }
    }
} 